import React, { useState, useEffect } from 'react';
import '../infoPages/Feeding.css'
import { Button } from '@mui/material';
import axios from 'axios';


function SettingPage() {
    const [type, setType] = useState("");
    const [subtype, setSubtype] = useState("");
    const [typeId, setTypeId] = useState("");
    const [types, setTypes] = useState([]);
    const [subtypes, setSubtypes] = useState([]);


    

    const handleType = (event) => {
        setType(event.target.value);
    };

    const handleTypeId = (event) => {
        setTypeId(event.target.value);
    }

    useEffect(() => {
        if(typeId !== ""){
            fetchSubtypes()
        }
    }, [typeId])

    const handleSubType = (event) => {
        setSubtype(event.target.value);
    };

    const addType = () => {
        const headers = {
            'Authorization': `Bearer ${localStorage.getItem('access')}`,
        };
        const body = {
            name: type
        }
        axios.post(`${process.env.REACT_APP_API_BASE_URL}/types`, body, {headers}).then((response) => {
            setType("")
        })
    }

    const addSubType = () => {
        const headers = {
            'Authorization': `Bearer ${localStorage.getItem('access')}`,
        };
        const body = {
            name: subtype,
            type_id: typeId
        }
        axios.post(`${process.env.REACT_APP_API_BASE_URL}/subtypes`, body, {headers}).then((response) => {
            setSubtype("")
        })

    }
    useEffect(() => {
        if(type===""){
            fetchTypes()
        }
    }, [type])
    useEffect(() => {
        if(subtype===""){
            fetchSubtypes()
        }
    }, [subtype])



    const fetchSubtypes = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const response = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/subtypes${typeId!== ""? "?types="+typeId:""}`, {headers});
            setSubtypes(response.data.subtypes);
        } catch (error) {
            console.error('Error fetching subtypes:', error);
        }
    };
    const fetchTypes = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const response = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/types`, {headers});
            setTypes(response.data.typess);
        } catch (error) {
            console.error('Error fetching subtypes:', error);
        }

    };

    const deleteType = (event) => {
        if (window.confirm("Вы уверены, что хотите удалить тип?")) {
        const headers = {
            'Authorization': `Bearer ${localStorage.getItem('access')}`,
        };
        axios.delete(`${process.env.REACT_APP_API_BASE_URL}/types?id=${event.target.value}`,  {headers}).then((response)=>{
            fetchTypes()
        }).catch((err) => {
            if(err.response.status == 500){
                window.alert('Тип нельзя удалить, так как он связан с оборудованием!')
            }
        })
    }
    }

    const deleteSubType = (event) => {
        if (window.confirm("Вы уверены, что хотите удалить подтип?")) {
        const headers = {
            'Authorization': `Bearer ${localStorage.getItem('access')}`,
        };
        axios.delete(`${process.env.REACT_APP_API_BASE_URL}/subtypes?id=${event.target.value}`,  {headers}).then((response)=>{
            fetchSubtypes()
        }).catch((err) => {
            if(err.response.status == 500){
                window.alert('Подтип нельзя удалить, так как он связан с оборудованием!')
            }
        })
    }
    }

    return(
        <div>
            <div className='input-table-container' style={{padding: 20}}>
            <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>
            <label>Наименование типа</label>
                <input className='input-form-table'
                    type={"text"}
                    value={type}
                    onChange={handleType}
                    style={{ borderColor: '#003AD0', margin: 0, width: '100%', height: 30 }}
                /> 
                <div style={{overflowY: "scroll", height:"200px"}}>
                    {types.map(type => (<option value={type.id} onClick={deleteType} style={{border: '2px solid', borderRadius: 10, padding: 7, margin: 9}}>{type.tname}</option>))}
                </div>
                        </div>
                        <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>
                <Button onClick={addType} sx={{ margin: 3, width: '95%', color: 'white', borderRadius: '15px', backgroundColor: '#003AD0', '&:focus': { backgroundColor: '#003AD0' }, fontStyle: { fontColor: 'white', fontSize: 20, fontWeight: 'bolder', fontFamily: "Montserrat" } }} variant={'contained'}>
                            Добавить
                        </Button>   
                        </div>
                        <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>
                        <label>Тип</label>

                        <select
                                value={typeId}
                                onChange={handleTypeId}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            >
                                <option value="">Выберите тип</option>
                                {types.map(sensor => (
                                    <option key={sensor.id} value={sensor.id}>{sensor.tname}</option>
                                ))}
                                </select>
                                </div>
                                <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>

            <label>Наименование подтипа</label>
                <input className='input-form-table'
                    type={"text"}
                    value={subtype}
                    onChange={handleSubType}
                    style={{ borderColor: '#003AD0', margin: 0, width: '100%', height: 30 }}
                /> 
                 <div style={{overflowY: "scroll", height:"200px"}}>
                 {subtypes.map(type => (<option value={type.id} onClick={deleteSubType} style={{border: '2px solid', borderRadius: 10, padding: 7, margin: 9}}>{type.name}</option>))}
                </div>
                        </div>
                        <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>
                <Button onClick={addSubType} sx={{ margin: 3, width: '95%', color: 'white', borderRadius: '15px', backgroundColor: '#003AD0', '&:focus': { backgroundColor: '#003AD0' }, fontStyle: { fontColor: 'white', fontSize: 20, fontWeight: 'bolder', fontFamily: "Montserrat" } }} variant={'contained'}>
                            Добавить
                        </Button>   
                        </div>
            </div>
        </div>
    )

}

export default SettingPage;
